package com.qms.tubu.widget;

import android.content.Context;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;

import com.qms.tubu.adapter.LoadMoreAdapter;

/**
 * Created by Mad on 2015/7/17.
 */
public class LoadMoreRecyclerView extends RecyclerView {
    public static int EACH_REQUEST_NUM=10;
    private LoadMoreAdapter mAdapter;
    private LinearLayoutManager mLayoutManager;
    private OnLoadMoreListener onLoadMoreListener;
    public LoadMoreRecyclerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.addOnScrollListener(mListener);
    }
    private OnScrollListener mListener=new OnScrollListener() {

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            if(mAdapter!=null && mLayoutManager!=null && mAdapter.getState()==LoadMoreAdapter.LOAD_INIT && dy>0)
            {
                int itemCount=mAdapter.getItemCount();
                int lastVisiblePosition=mLayoutManager.findLastVisibleItemPosition();
                if(lastVisiblePosition>=itemCount-2)
                {
                    if(onLoadMoreListener!=null)
                    {
                        mAdapter.setLoadState(LoadMoreAdapter.LOAD_START);
                        onLoadMoreListener.onLoadMore();
                    }
                }
            }
        }
    };
    public void loadFailed()
    {
        if(mAdapter!=null)
        {
            mAdapter.setLoadState(LoadMoreAdapter.LOAD_INIT);
        }
    }
    public void loadComplete(int loadNum)
    {
        if(mAdapter!=null) {
            if (loadNum<EACH_REQUEST_NUM)
                mAdapter.setLoadState(LoadMoreAdapter.LOAD_COMPLETE);
            else
                mAdapter.setLoadState(LoadMoreAdapter.LOAD_INIT);
        }
    }
    @Override
    public void setAdapter(Adapter adapter) {
        super.setAdapter(adapter);
        if(adapter instanceof LoadMoreAdapter)
        {
            mAdapter= (LoadMoreAdapter) adapter;
        }
    }

    public void setOnLoadMoreListener(OnLoadMoreListener onLoadMoreListener) {
        this.onLoadMoreListener = onLoadMoreListener;
    }

    @Override
    public void setLayoutManager(LayoutManager layout) {
        super.setLayoutManager(layout);
        if(layout instanceof LinearLayoutManager)
        {
            mLayoutManager= (LinearLayoutManager) layout;
        }
    }
    public interface OnLoadMoreListener{
        void onLoadMore();
    }
}
